package cn.yedong.basic.controller;

import cn.yedong.basic.util.AjaxResult;
import cn.yedong.basic.util.FastDfsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 接口：文件上传
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult uploadFile(@RequestPart MultipartFile file){
        try {
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件后缀
            String extName = originalFilename.substring(originalFilename.indexOf(".") + 1);

            String fileName = FastDfsUtils.upload(file.getBytes(), extName);
            return  AjaxResult.me().setObj(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败！");
        }
    }

    /**
     * 接口：文件删除
     * @param path
     * @return
     */
    @DeleteMapping
    public AjaxResult deleteFile(@RequestParam String path){
        try {
            //path=/group1/M00/03/8B/CgAIC2PeJFSAG_U3AD903OP41Wk022.jpg
            //获取组名
            path = path.substring(1);//group1/M00/03/8B/CgAIC2PeJFSAG_U3AD903OP41Wk022.jpg
            String groupName = path.substring(0, path.indexOf("/"));//group
            //获取文件名
            String fileName = path.substring(path.indexOf("/")+1);
            //调用工具类删除文件
            FastDfsUtils.delete(groupName,fileName);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败！");
        }
    }
}
